package com.abbas.smartCity.retroft;

import android.widget.Toast;

import androidx.annotation.NonNull;

import com.abbas.smartCity.App;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 对错误的统一处理
 *
 * @param <T> 请求的数据类型
 */
public abstract class ICallback<T> implements Callback<T> {

    private JSONObject jsonObject;

    @Override
    public void onResponse(@NonNull Call<T> call, Response<T> response) {
        if (response.isSuccessful() && response.body() != null) {
            String objJson = App.gson.toJson(response.body());
            try {
                jsonObject = new JSONObject(objJson);
                int resCode = jsonObject.optInt("code");
                String resMsg = jsonObject.optString("msg");
                App.getHandler().post(() -> {//不确定这个handler有没有用
                    if (resCode >= 200 && resCode <= 299) {
                        onSuccess(call, response.body());
                    } else if (resCode >= 500 && resCode <= 599) {
                        onActFailure(call, resMsg, response);
                    }
                });
            } catch (JSONException e) {
                onActFailure(call, "数据解析失败", response);
                throw new RuntimeException(e);
            }
        } else {
            onActFailure(call, "数据出错，请尝试再次连接", response);
        }
    }

    @Override
    public void onFailure(@NonNull Call<T> call, @NonNull Throwable throwable) {
        onActFailure(call, "请求失败，请检查网络。", null);
    }

    /**
     * 数据访问成功后的回调
     *
     * @param call Call
     * @param data 数据
     */
    public abstract void onSuccess(Call<T> call, T data);

    /**
     * 请求失败后都会到这里，无论是网络问题，解析失败，总之没有成功拿到数据都会调用此方法
     *
     * @param call     call
     * @param msg      massage
     * @param response response
     */
    public void onActFailure(Call<T> call, String msg, Response<T> response) {
        Toast.makeText(App.getContext(), msg, Toast.LENGTH_SHORT).show();
    }


}
